import dayjs from "dayjs";
import authService from "../../services/auth.service";
import personalCenterService from "../../services/personal-center.service";
import { WX_STORAGE_KEY_TOKEN, WX_STORAGE_KEY_USER_PROFILE } from "../../utils/constants";

// pages/profile/profile.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    username: '',
    nickname: '',
    phone: '',
    email: '',
    realName: '',
    birthday: '',
    description: '',
    showDatePicker: false,
    datePickerValue: undefined,
    minDate: new Date(1980, 0, 1).getTime(),
    maxDate: new Date().getTime(),
  },
  async load() {
    try {
      const profile = await personalCenterService.retrieve();
      wx.setStorageSync(WX_STORAGE_KEY_USER_PROFILE, profile);

      const currentUser = profile.user;
      let datePickerValue = null;
      if (profile.user && profile.user.birthday) {
        const date = dayjs(this.data.birthday);
        datePickerValue = date.valueOf();
      }

      this.setData({
        id: currentUser && currentUser.id,
        username: currentUser && currentUser.username,
        nickname: currentUser && currentUser.nickname,
        phone: currentUser && currentUser.phone,
        email: currentUser && currentUser.email,
        realName: currentUser && currentUser.realName,
        birthday: currentUser && currentUser.birthday,
        introduce: currentUser && currentUser.introduce,
        datePickerValue: datePickerValue,
      });
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      if (err.data && err.data.errorCode == "Auth_Exception_0005") {
        this.frontLogout();
      }
      throw err;
    } finally {
    }
  },
  showBirthdayPicker() {
    this.setData({
      showDatePicker: true,
    });
  },
  onDatePickerClose() {
    this.setData({
      showDatePicker: false,
    });
  },
  updateBirthday(event) {
    const date = dayjs(event.detail);
    
    this.setData({
      birthday: date.format("YYYY-MM-DD"),
      datePickerValue: event.timeStamp,
      showDatePicker: false,
    });
  },
  async save() {
    try {
      const body = {
        id: this.data.id,
        username: this.data.username,
        nickname: this.data.nickname,
        phone: this.data.phone,
        email: this.data.email,
        realName: this.data.realName,
        birthday: this.data.birthday,
        introduce: this.data.introduce,
      }
      await personalCenterService.update(body);
      this.load();
      wx.showToast({
        title: '保存成功',
        icon: "success"
      });
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      throw err;
    } finally {
    }
  },
  changePassword() {
    wx.navigateTo({
      url: '/pages/change-password/change-password',
    })
  },
  async logout() {
    try {
      // 后端注销token
      await authService.logout();
    } catch (err) {
      wx.showToast({
        title: err.data && err.data.message || err.errMsg,
        icon: 'error'
      });
      if (err.data && err.data.errorCode == "Auth_Exception_0005") {
        this.frontLogout();
      }
      throw err;
    } finally {
      this.frontLogout();
    }
  },

  frontLogout() {
    // 前端取消授权
    wx.removeStorageSync(WX_STORAGE_KEY_TOKEN);
    wx.removeStorageSync(WX_STORAGE_KEY_USER_PROFILE);
    // 跳转至主页
    wx.navigateTo({
      url: '/pages/home/home',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.load();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})